package hk.m4s.lr.repair.test.ui.goods;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.baseui.UeBaseActivity;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.HomeIconInfo;
import hk.m4s.lr.repair.test.model.ShopModel;
import hk.m4s.lr.repair.test.service.AccountSerive;
import hk.m4s.lr.repair.test.ui.adapter.CarShopLikeAdapter;
import hk.m4s.lr.repair.test.ui.adapter.CardRvAdapter;
import hk.m4s.lr.repair.test.ui.adapter.GoodsAdapter;
import hk.m4s.lr.repair.test.views.CustomSnapHelper;
import hk.m4s.lr.repair.test.views.GradationScrollView;
import hk.m4s.lr.repair.test.views.InnerGridView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/13.
 * 汽保商城
 */

public class GoodsShopActivity extends UeBaseActivity implements View.OnClickListener, GoodsAdapter.Listeners,ObservableScrollViewCallbacks{
    private Context context;
    private LayoutInflater inflater;
    private Banner banner;
    private ImageView shopBack, searchImg, shopping_car;
    private InnerGridView car_shop_like, car_guess_like;
    private LinearLayout click_select, shopTitleBar,titleBar,tabLout,car_shop_grid;
    private TextView carNum, lookMore, device_id,allBtn;
    private RelativeLayout flashSale,search_backgroud;
    private ObservableScrollView car_scrollview;
    private TabLayout tabLayout,tabs;
    private GoodsAdapter goodsAdapter;
    private CarShopLikeAdapter carShopLikeAdapter;
    private RecyclerView rv;
    private List<HomeIconInfo> mPagerOneData = new ArrayList<>();
    public static List<ShopModel.ListRecommendBean> likeList = new ArrayList<>();
    public static List<ShopModel.ListGoodsBean> guessList = new ArrayList<>();
    public static List<ShopModel.ListGoodsBean> carList = new ArrayList<>();
    private int height;
    private int mPrevScrollY;
    private int mFlexibleSpaceImageHeight;
    private int mActionBarSize=60;
    private static final float MAX_TEXT_SCALE_DELTA = 0.3f;
    private static final boolean TOOLBAR_IS_STICKY = true;
    /**
     * 总的页数
     */
    private int pageCount;
    /**
     * 每一页显示的个数
     */
    private int pageSize = 4;
    /**
     * 当前显示的是第几页
     */
    private int curIndex = 0;
    private List<View> mPagerList;
    private List<ShopModel.ListAdGoodsBean> adList = new ArrayList<>();

    private int mToolbarColor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_goods_shop);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        hiddenFooter();
        hiddenHeader();
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub
        context = this;
        inflater = LayoutInflater.from(context);
        findBaseView();
    }

    private void findBaseView() {
        car_scrollview = (ObservableScrollView) findViewById(R.id.car_scrollview);
        car_scrollview.setScrollViewCallbacks(this);
        banner = (Banner) findViewById(R.id.banner);
        mFlexibleSpaceImageHeight=260;
        mActionBarSize = 55;
        mToolbarColor = getResources().getColor(R.color.colorBg);
        tabLayout = (TabLayout) findViewById(R.id.tab);

        tabLout= (LinearLayout) findViewById(R.id.tabLayout);
        car_shop_grid= (LinearLayout) findViewById(R.id.car_shop_grid);
        car_shop_like = (InnerGridView) findViewById(R.id.car_shop_like);
        car_guess_like = (InnerGridView) findViewById(R.id.car_guess_like);
        rv = (RecyclerView) findViewById(R.id.rv);
        shopBack = (ImageView) findViewById(R.id.shopBack);
        searchImg = (ImageView) findViewById(R.id.searchImg);
        allBtn= (TextView) findViewById(R.id.allBtn);
        search_backgroud=(RelativeLayout)findViewById(R.id.search_backgroud);
        carNum = (TextView) findViewById(R.id.carNum);
        lookMore = (TextView) findViewById(R.id.lookMore);
        device_id = (TextView) findViewById(R.id.device_id);
        shopping_car = (ImageView) findViewById(R.id.shopping_class);
        click_select = (LinearLayout) findViewById(R.id.click_select);
        shopTitleBar = (LinearLayout) findViewById(R.id.shopTitleBar);
        titleBar= (LinearLayout) findViewById(R.id.titleBar);
        flashSale = (RelativeLayout) findViewById(R.id.flashSale);
        if (!TOOLBAR_IS_STICKY) {
            shopTitleBar.setBackgroundResource(0);
            shopBack.setImageResource(R.mipmap.back);
            searchImg.setImageResource(R.mipmap.searchbtn_img);
            click_select.setBackgroundResource(R.drawable.selector_jianbian_black);
            device_id.setTextColor(Color.parseColor("#ffffff"));
            shopping_car.setImageResource(R.mipmap.goodsca);
        }
        rv.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        CustomSnapHelper mMySnapHelper = new CustomSnapHelper();
        mMySnapHelper.attachToRecyclerView(rv);
        carShopLikeAdapter = new CarShopLikeAdapter(context, likeList);
        car_shop_like.setAdapter(carShopLikeAdapter);
        goodsAdapter = new GoodsAdapter(context, guessList);
        car_guess_like.setAdapter(goodsAdapter);
        car_shop_like.setOnItemClickListener(clickItems);
        click_select.setOnClickListener(this);
        shopping_car.setOnClickListener(this);
        flashSale.setOnClickListener(this);
        lookMore.setOnClickListener(this);
        car_shop_grid.setOnClickListener(this);
        allBtn.setOnClickListener(this);
        tabLayout.addTab(tabLayout.newTab().setText("店铺首页"), true);
        tabLayout.addTab(tabLayout.newTab().setText("全部商品"));
        tabLayout.addTab(tabLayout.newTab().setText("新品上架"));
        tabLayout.addTab(tabLayout.newTab().setText("热卖商品"));
        initData();
        getIndex();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_select:
                Intent in = new Intent(GoodsShopActivity.this, SearchActivity.class);
                startActivity(in);
                break;
            case R.id.flashSale:
                Intent flashin = new Intent(GoodsShopActivity.this, FlashSaleActivity.class);
                startActivity(flashin);
                break;
            case R.id.lookMore:
                Intent lookin = new Intent(GoodsShopActivity.this, FlashSaleActivity.class);
                startActivity(lookin);
                break;
            case R.id.car_shop_grid:
                Intent lookshopin = new Intent(GoodsShopActivity.this, ShopRecommedActivity.class);
                startActivity(lookshopin);
                break;
            case R.id.shopping_class:
                Intent lookclassshopin = new Intent(GoodsShopActivity.this, ShopClassificationActivity.class);
                startActivity(lookclassshopin);
                break;
            case R.id.allBtn:
                  finish();
                break;
        }
    }

    public void getIndex() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("userId", SharedPreferencesUtils.getSharedPreferences(Constant.userId, ""));
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        AccountSerive.index(context, parmas, new ResponseCallback<ShopModel>() {
            @Override
            public void onSuccess(ShopModel userinfoModel) {
                if (userinfoModel.getListAdGoods() != null) {
                    adList.clear();
                    adList.addAll(userinfoModel.getListAdGoods());
                    //设置指示器位置（当banner模式中有指示器时）
                    banner.setIndicatorGravity(BannerConfig.RIGHT);
                    //设置图片加载器
                    banner.setImageLoader(new GlideImageLoader());
                    //设置图片集合
                    banner.setImages(adList);
                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
                    rv.setAdapter(new CardRvAdapter(GoodsShopActivity.this, adList));
                }

            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });

    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            ShopModel.ListAdGoodsBean bean = (ShopModel.ListAdGoodsBean) path;
            if (bean != null) {
                Glide.with(context).load(bean.getImage()).placeholder(R.mipmap.sebei_logo).error(R.mipmap.sebei_logo).into(imageView);
            }
        }

    }


    private void initData() {
        mPagerList = new ArrayList<View>();
        String[] iconName = getResources().getStringArray(R.array.home_bar_labels);
        //获取图片资源数组,方法是obtainTypeArray
        TypedArray typedArray = getResources().obtainTypedArray(R.array.home_bar_icon);
        for (int i = 0; i < iconName.length; i++) {
            //把数据装在第一个集合里,给第一个GridKView用
            HomeIconInfo homeIconInfo = new HomeIconInfo(iconName[i], typedArray.getResourceId(i, 0));
            //将iconName获取到的文本资源添加到第一个GridView数组里
            mPagerOneData.add(homeIconInfo);

        }
        pageCount = (int) Math.ceil(mPagerOneData.size() * 1.0 / pageSize);
        //设置适配器
        //超实惠
        likeList.clear();
        guessList.clear();
        ShopModel.ListRecommendBean bean1 = new ShopModel.ListRecommendBean();
        bean1.setImages("");
        bean1.setGoods_name("超能双铂金火花塞1支装");
        bean1.setGoods_id("1");
        bean1.setPrice("20");
        ShopModel.ListRecommendBean bean2 = new ShopModel.ListRecommendBean();
        bean2.setImages("");
        bean2.setGoods_name("车载尘器吸力超强120w干湿两用");
        bean2.setGoods_id("2");
        bean2.setPrice("20");
        ShopModel.ListRecommendBean bean3 = new ShopModel.ListRecommendBean();
        bean3.setImages("");
        bean3.setGoods_name("美国杜邦空调清洗剂");
        bean3.setGoods_id("3");
        bean3.setPrice("20");
        likeList.add(bean1);
        likeList.add(bean2);
        likeList.add(bean3);
        carShopLikeAdapter.notifyDataSetChanged();
        ShopModel.ListGoodsBean bean4 = new ShopModel.ListGoodsBean();
        bean4.setImages("");
        bean4.setGoods_name("超能双铂金火花塞1支装");
        bean4.setGoods_id("4");
        bean4.setPrice("20");
        ShopModel.ListGoodsBean bean5 = new ShopModel.ListGoodsBean();
        bean5.setImages("");
        bean5.setGoods_name("车载尘器吸力超强120w干湿两用");
        bean5.setGoods_id("5");
        bean5.setPrice("20");
        ShopModel.ListGoodsBean bean6 = new ShopModel.ListGoodsBean();
        bean6.setImages("");
        bean6.setGoods_name("美国杜邦空调清洗剂");
        bean6.setGoods_id("6");
        bean6.setPrice("20");
        ShopModel.ListGoodsBean bean7 = new ShopModel.ListGoodsBean();
        bean7.setImages("");
        bean7.setGoods_name("美国杜邦空调清洗剂");
        bean7.setGoods_id("7");
        bean7.setPrice("20");
        guessList.add(bean4);
        guessList.add(bean5);
        guessList.add(bean6);
        guessList.add(bean7);
        goodsAdapter.setLoadingListener(this);
        goodsAdapter.notifyDataSetChanged();

    }

    class ViewPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public ViewPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));
            return (mViewList.get(position));
        }

        @Override
        public int getCount() {
            if (mViewList == null)
                return 0;
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    public void addCar(ShopModel.ListGoodsBean newsModel) {
        carList.add(newsModel);
        carNum.setVisibility(View.VISIBLE);
        carNum.setText(carList.size() + "");
    }

    AdapterView.OnItemClickListener clickItems = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            ShopModel.ListRecommendBean model = likeList.get(arg2);

            Intent aboutIntent = new Intent(GoodsShopActivity.this, GoodsEventActivity.class);
            aboutIntent.putExtra("goods_id", model.getGoods_id());
            startActivity(aboutIntent);
        }

    };

    /**
     * 获取顶部图片高度后，设置滚动监听
     */

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        float flexibleRange = mFlexibleSpaceImageHeight - mActionBarSize;
        int minOverlayTransitionY = mActionBarSize - 260;
        if (TOOLBAR_IS_STICKY) {
//            // Change alpha of toolbar background
            if (-scrollY + mFlexibleSpaceImageHeight <= mActionBarSize) {
                shopTitleBar.setBackgroundResource(R.color.text_white);
                click_select.setBackgroundResource(R.drawable.btn_empy_gray);
                shopBack.setImageResource(R.mipmap.back_gray);
                searchImg.setImageResource(R.mipmap.search_gray);
                device_id.setTextColor(Color.parseColor("#000000"));
                shopping_car.setImageResource(R.mipmap.goods_ca_gray);

            } else {
                shopTitleBar.setBackgroundResource(0);
                shopBack.setImageResource(R.mipmap.back);
                searchImg.setImageResource(R.mipmap.searchbtn_img);
                click_select.setBackgroundResource(R.drawable.selector_jianbian_black);
                device_id.setTextColor(Color.parseColor("#ffffff"));
                shopping_car.setImageResource(R.mipmap.goodsca);
            }
        } else {
            // Translate Toolbar
            if (scrollY < mFlexibleSpaceImageHeight) {
                ViewHelper.setTranslationY(search_backgroud, 0);
            } else {
                ViewHelper.setTranslationY(search_backgroud, -scrollY);
            }
        }
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }
}
